<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>扫码测试系统</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
    <style>
        body {
            font-family: 'Inter', sans-serif;
            background-color: #f4f4f9;
        }

        .scan-container {
            max-width: 600px;
            margin: 3rem auto;
            padding: 2.5rem;
            background: white;
            border-radius: 1.5rem;
            box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
            transition: transform 0.3s ease;
        }

        .scan-container:hover {
            transform: translateY(-5px);
        }

        .scan-input {
            width: 100%;
            padding: 1rem;
            border: 1px solid #e5e7eb;
            border-radius: 0.75rem;
            margin: 0.75rem 0;
            font-size: 1rem;
            transition: border-color 0.3s ease;
        }

        .scan-input:focus {
            outline: none;
            border-color: #3b82f6;
        }

        .result-box {
            padding: 1.25rem;
            border-radius: 0.75rem;
            margin: 1.5rem 0;
            font-weight: 600;
            text-align: center;
            transition: background-color 0.3s ease;
        }

        .success {
            background: #dcfce7;
            color: #166534;
        }

        .fail {
            background: #fee2e2;
            color: #b91c1c;
        }

        .info {
            background: #e0f2fe;
            color: #075985;
        }

        .log-box {
            background: #f3f4f6;
            border-radius: 0.75rem;
            padding: 1.25rem;
            min-height: 120px;
            max-height: 250px;
            overflow-y: auto;
            white-space: pre-wrap;
        }

        button {
            transition: background-color 0.3s ease, transform 0.3s ease;
        }

        button:hover {
            transform: scale(1.05);
        }
    </style>
</head>

<body>
    <div class="scan-container">
        <h1 class="text-3xl font-bold text-gray-900 mb-5 text-center">扫码测试系统</h1>
        <!-- 扫码输入区 -->
        <div class="space-y-4">
            <div>
                <label class="text-sm font-medium text-gray-700">扫码1内容：</label>
                <input type="text" id="scan1Input" class="scan-input" placeholder="请扫描或输入扫码1内容">
            </div>
            <div>
                <label class="text-sm font-medium text-gray-700">扫码2内容：</label>
                <input type="text" id="scan2Input" class="scan-input" placeholder="请扫描或输入扫码2内容">
            </div>
        </div>
        <!-- 验证按钮 -->
        <button id="validateBtn"
            class="w-full bg-blue-600 text-white py-3 px-4 rounded-md hover:bg-blue-700 transition-colors mt-6">
            验证绑定条件
        </button>
        <!-- 结果显示区 -->
        <div id="resultArea" class="result-box info">请输入扫码内容后点击验证</div>
        <!-- 日志显示区 -->
        <div class="mt-6">
            <h2 class="text-lg font-medium text-gray-700 mb-3">操作日志</h2>
            <div id="logArea" class="log-box"></div>
        </div>
    </div>
    <script>
        // 记录日志
        function logMessage(message) {
            const logArea = document.getElementById('logArea');
            const logEntry = document.createElement('p');
            logEntry.textContent = `${new Date().toLocaleString()}: ${message}`;
            logArea.appendChild(logEntry);
            logArea.scrollTop = logArea.scrollHeight;
        }

        // 从服务器获取设置
        async function getSettings() {
            try {
                logMessage('开始从服务器获取设置...');
                const response = await fetch('/settings');
                if (!response.ok) {
                    throw new Error(`请求失败，状态码: ${response.status}`);
                }
                logMessage(`获取设置请求返回状态码: ${response.status}`);
                return await response.json();
            } catch (error) {
                logMessage(`获取设置失败: ${error.message}`);
                console.error('获取设置失败:', error);
                return null;
            }
        }

        // 提取扫码内容的指定位置值
        function extractValue(scanText, start, end) {
            if (!scanText) return "";
            return scanText.slice(start - 1, end) || "";
        }

        // 验证单个比对条件
        function validateCondition(scan1Text, scan2Text, condition) {
            const [s1Start, s1End, s2Start, s2End] = condition;
            const value1 = extractValue(scan1Text, s1Start, s1End);
            const value2 = extractValue(scan2Text, s2Start, s2End);
            return value1 === value2 && value1!== "" && value2!== "";
        }

        // 主验证逻辑（双条件同时满足）
        async function mainValidation() {
            const scan1 = document.getElementById('scan1Input').value.trim();
            const scan2 = document.getElementById('scan2Input').value.trim();
            const resultEl = document.getElementById('resultArea');

            logMessage('开始执行绑定验证...');
            const settings = await getSettings();
            // 检查是否有设置
            if (!settings ||!settings.compare) {
                logMessage('未找到参数设置，请先配置参数');
                resultEl.className = "result-box fail";
                resultEl.textContent = "❌ 错误：未找到参数设置，请先配置参数";
                // 验证失败后将焦点回到扫码1输入框
                document.getElementById('scan1Input').focus();
                return;
            }
            // 检查扫码内容是否为空
            if (!scan1 ||!scan2) {
                logMessage('请输入完整的扫码1和扫码2内容');
                resultEl.className = "result-box info";
                resultEl.textContent = "ℹ️ 请输入完整的扫码1和扫码2内容";
                // 扫码内容为空时将焦点回到扫码1输入框
                document.getElementById('scan1Input').focus();
                return;
            }

            // 尝试两种扫码顺序
            const compare1 = settings.compare.compare1;
            const compare2 = settings.compare.compare2;

            const condition1Order1 = validateCondition(scan1, scan2, compare1);
            const condition2Order1 = validateCondition(scan1, scan2, compare2);

            const condition1Order2 = validateCondition(scan2, scan1, compare1);
            const condition2Order2 = validateCondition(scan2, scan1, compare2);

            const isOrder1Valid = condition1Order1 && condition2Order1;
            const isOrder2Valid = condition1Order2 && condition2Order2;

            if (isOrder1Valid || isOrder2Valid) {
                logMessage('绑定成功：双条件均满足');
                resultEl.className = "result-box success";
                resultEl.textContent = "✅ 绑定成功：双条件均满足";

                // 发送绑定成功的数据到后端
                try {
                    const response = await fetch('/save-binding-data', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            scan1: scan1,
                            scan2: scan2
                        })
                    });
                    if (!response.ok) {
                        throw new Error(`保存绑定数据失败，状态码: ${response.status}`);
                    }
                    logMessage('绑定数据保存成功');
                } catch (error) {
                    logMessage(`保存绑定数据失败: ${error.message}`);
                }

                // 清空扫码框
                document.getElementById('scan1Input').value = '';
                document.getElementById('scan2Input').value = '';
            } else {
                logMessage(`绑定失败：两种扫码顺序均不满足双条件`);
                resultEl.className = "result-box fail";
                resultEl.textContent = `❌ 绑定失败：两种扫码顺序均不满足双条件`;
            }

            // 无论验证结果如何，都将焦点回到扫码1输入框
            document.getElementById('scan1Input').focus();
        }

        // 事件绑定
        document.addEventListener('DOMContentLoaded', () => {
            // 按钮点击事件
            document.getElementById('validateBtn').addEventListener('click', mainValidation);

            // 输入框回车事件
            const scan1Input = document.getElementById('scan1Input');
            const scan2Input = document.getElementById('scan2Input');
            scan1Input.focus();

            scan1Input.addEventListener('keydown', (e) => {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    scan2Input.focus();
                }
            });
            scan2Input.addEventListener('keydown', (e) => {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    mainValidation();
                }
            });
        });
    </script>
</body>

</html>